package hfs

import (
	"os"
	"path/filepath"
	"strings"

	"github.com/gin-gonic/gin"
)

func (s *httpFileServerImpl) StaticFileMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		path := c.Request.URL.Path

		// 检查是否匹配静态文件路径模式
		if strings.HasPrefix(path, "/") {
			parts := strings.Split(path, "/")
			if len(parts) > 1 {
				virtualDir := parts[1]

				s.mutex.RLock()
				physicalPath, exists := s.mappings[virtualDir]
				s.mutex.RUnlock()

				if exists {
					filePath := filepath.Join(physicalPath, strings.Join(parts[2:], "/"))
					if _, err := os.Stat(filePath); err == nil {
						c.File(filePath)
						c.Abort()
						return
					}
				}
			}
		}

		c.Next()
	}
}

func (s *httpFileServerImpl) AllowedCORSMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 设置允许跨域的响应头
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*") // 允许所有域名跨域，生产环境可指定具体域名
		c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Authorization")
		c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")

		// 如果是预检请求，直接返回204状态码，不继续处理
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	}
}
